<template>
  <div class="layout">
    <nav :class="{'layout-hide-text': !toggle}">
      <div style="background-color: #3a3f51;">
        <a class="header-logo">
          <img src="../assets/logo.png" alt="." class="header-img">
          <span class="header-span">微商城</span>
        </a>
      </div>
      <Menu :theme="theme" :width="menuWidth" :style="{ 'min-height' : clientHeight - 52 + 'px'}" @on-select="menuClick" :active-name="activeMenuName"
            :open-names="openMenuNames">
        <Submenu :name="menu.url" v-for="(menu, index) in menus"
                 :key="index" v-if="menu.parentId == null">
          <template slot="title">
            <Icon :type="menu.themeJson.icon" size="15" :color="menu.themeJson.color" style="margin-right: 3px;"></Icon>
            <span class="layout-text">{{menu.name}}</span>
          </template>
          <Menu-item :name="child.url"
                     v-for="child in menus"
                     :key="child.id" v-if="child.parentId == menu.id">
            <Icon :type="child.themeJson.icon" :size="iconSize"></Icon>
            <span class="layout-text">{{child.name}}</span>
          </Menu-item>
        </Submenu>
      </Menu>
    </nav>
    <div style="width: 100%">
      <Affix>
        <div class="layout-header">
          <div class="layout-ceiling" style="line-height: 50px;font-size: 18px;">
            <div class="layout-ceiling-main">
              <span style="font-size: 14px;">
                欢迎用户：
                <span style="color: #4285f4">{{loginName}}</span>
              </span>
              <span style="margin-left: 10px">
                    <a href="javascript:void(0)" @click="logout" class="header-menu">
                        <Icon type="android-exit" style="color:red;"></Icon>
                        <span style="cursor:pointer;">退出系统</span>
                    </a>
                    <a href="javascript:void(0)" @click="resetPwd" class="header-menu">
                        <Icon type="edit" style="color:#657180;"></Icon>
                        <span style="cursor:pointer;">修改密码</span>
                    </a>
                </span>
            </div>
          </div>
        </div>
      </Affix>

      <div class="layout-content" :style="{ 'min-height' : clientHeight - 124+ 'px'}">
        <div class="layout-content-main">
          <transition>
            <router-view></router-view>
          </transition>
        </div>
      </div>

      <!--修改密码弹出层-->
      <div>
        <Modal v-model="passwordModel" title="修改密码" :mask-closable="false">
          <Form ref="passwordForm" :model="pwdForm" :rules="pwdRule" :label-width="100">
            <Form-item prop="originPwd" label="原密码">
              <i-input type="password" v-model="pwdForm.originPwd" placeholder="请输入原密码">
                <Icon type="ios-locked-outline" slot="prepend"></Icon>
              </i-input>
            </Form-item>
            <Form-item label="新密码" prop="newPwd">
              <i-input type="password" v-model="pwdForm.newPwd" placeholder="请输入新密码">
                <Icon type="ios-locked-outline" slot="prepend"></Icon>
              </i-input>
            </Form-item>
            <Form-item label="确认密码" prop="surePwd">
              <i-input type="password" v-model="pwdForm.surePwd" placeholder="确认密码">
                <Icon type="ios-locked-outline" slot="prepend"></Icon>
              </i-input>
            </Form-item>
          </Form>
          <div slot="footer">
            <Button type="primary" @click="handlePasswordSubmit('passwordForm')">提交</Button>
            <Button type="ghost" @click="resetPasswordForm('passwordForm')">重置</Button>
            <Button type="ghost" @click="passwordModel=false">取消</Button>
          </div>
        </Modal>
      </div>
      <div class="layout-copy">
        2017 &copy; 微商城 <a href="http://weishop.ueboot.com" target="_blank">http://weishop.ueboot.com</a>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from "axios";
  import values from "../utils/values";

  export default {
    data() {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          callback();
        }
      };
      const validatePassCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.pwdForm.newPwd) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        loginName: null,//登录账号名称
        lastLoginTime: '',//上次登录时间
        state: '',
        toggle: true,
        theme: 'dark',
        menuWidth: "200px",
        activeMenuName: "",
        menus: [],
        openMenuNames: [],
        clientHeight: document.documentElement.clientHeight,
        passwordModel: false,//弹出修改密码弹出层
        pwdForm: {
          originPwd: '',
          newPwd: '',
          surePwd: "",
        },
        pwdRule: {
          originPwd: [
            {required: true, message: '请输入原密码', trigger: 'blur'}
          ],
          newPwd: [
            {required: true, validator: validatePass, trigger: 'blur'}
          ],
          surePwd: [
            {required: true, validator: validatePassCheck, trigger: 'change'}
          ],
        },
      }
    },
    methods: {
      init: function () {
        axios.get("/menus").then(response => {
          this.menus = response.body;
          this.activeMenuName = this.$route.name;
          //让菜单展开到路径匹配的位置
          let matched = this.$route.matched;
          matched.forEach((m) => {
            if (!m.parent) {
              this.openMenuNames.push(m.name);
            }
          });
        }).catch(response => {
          console.log(response);
        })
      },
      menuClick(path) {
        this.$router.push(path);
      },
      logout() {
        //退出系统
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定要退出当前系统吗',
          onOk: () => {
            axios.post("/logout").then((data) => {
              this.$Message.success('退出成功!');
              this.$router.push({name: 'login'});
            }, (response) => {
              this.$log.d(response);
              this.$Notice.error({
                title: "系统异常",
                desc: response.message ? response.message : "系统或网络异常"
              });
            });
          }
        });
      },
      resetPwd(name) {
        //修改密码
        this.resetPasswordForm('passwordForm');
        this.passwordModel = true;
      },
      operationConfig() {
        let sessionUser = JSON.parse(sessionStorage.getItem(values.storage.user)) || {};
        let userType = sessionUser.userType;
        this.routerConfig.routes.forEach(function (item) {
          if (item.role == userType) {
            item.isHide = false
          } else {
            item.isHide = true
          }
        });
      },
      resetPasswordForm(name) {
        this.$refs[name].resetFields();
      },
      handlePasswordSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            let sessionUser = JSON.parse(sessionStorage.getItem(values.storage.user));
            let jsonData = {
              oldPassword: this.pwdForm.originPwd,
              newPassword: this.pwdForm.newPwd,
              userType: sessionUser.userType,
              userId: sessionUser.userId
            };
            this.$ajax.post("/public/api/updatePassword", jsonData).then((data) => {
              //关闭浮层
              this.passwordModel = false;
              this.$Modal.success({
                title: "系统提示",
                content: "修改成功,下次登录请用新密码登录, 谢谢!"
              });
            }, (response) => {
              this.$log.d(response);
              this.$Notice.error({
                title: "系统异常",
                desc: response.message ? response.message : "系统或网络异常"
              });
            });
          }
        });
      },
    },
    computed: {
      iconSize() {
        return this.toggle ? "14px" : "24px";
      }
    },
    created() {
      this.init();
    },
    mounted() {
      this.loginName = sessionStorage.getItem("userName");//登录账号名称
    }
  }
</script>

<style scoped>
  *[v-cloak] {
    display: none;
  }

  .layout {
    /*border: 1px solid #d7dde4;*/
    background: #f5f7f9;
    height: 100%;
    display: flex;
    flex-wrap: nowrap;
  }

  .layout-breadcrumb {
    width: 100%;
    height: 48px;
    padding: 10px 20px 0px 0px;
  }

  .layout-content {
    min-height: 200px;
    margin: 15px 15px 0 15px;
    /*overflow: hidden;*/
    background: #fff;
    border-radius: 4px;
  }

  .layout-content-main {
    width: 100%;
    padding: 10px;
  }

  .layout-copy {
    text-align: center;
    padding: 5px 0 5px;
    color: #9ea7b4;
  }

  .layout-header {
    height: 50px;
    background: #fff;
    padding-right: 15px;
    padding-left: 15px;
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(0, 0, 0, 0.05);
  }

  .layout-logo-left {
    width: 90%;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    margin: 15px auto;
  }

  .layout-ceiling-main a {
    color: #9ba7b5;
  }

  /*隐藏文字*/
  .layout-hide-text .layout-text {
    display: none;
  }

  /*隐藏向下箭头*/
  .layout-hide-text .ivu-menu-vertical .ivu-menu-submenu-title-icon {
    display: none;
  }

  .ivu-col {
    transition: width .2s ease-in-out;
  }

  .header-logo {
    background: 0 0;
    text-decoration: none;
    outline: 0;
    cursor: pointer;
    transition: color .2s ease;
    display: inline-block;
    float: none !important;
    height: auto;
    padding: 0 20px;
    font-size: 20px;
    font-weight: 700;
    line-height: 50px;
    text-align: center;
    color: #eaebed !important;
  }

  .header-img {
    border-style: none;
    display: inline-block !important;
    max-height: 20px;
    margin-top: -4px;
    vertical-align: middle;
    visibility: visible;
    border-style: none;
    border: 0;
    color: #eaebed !important;
  }

  .header-span {
    box-sizing: border-box;
    color: rgb(88, 102, 110);
    cursor: pointer;
    display: inline;
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", 微软雅黑, Arial, sans-serif;
    font-size: 20px;
    font-weight: bold;
    height: auto;
    line-height: 50px;
    margin-left: 5px;
    text-align: center;
  }

  .layout-ceiling-main .header-menu {
    font-size: 14px;
    display: inline-block;
    text-align: center;
    width: 90px;
  }

  .caret {
    display: inline-block;
    width: 0;
    height: 0;
    margin-left: 2px;
    vertical-align: middle;
    border-top: 4px dashed;
    border-right: 4px solid transparent;
    border-left: 4px solid transparent;
  }

  .layout-ceiling-main a {
    color: rgb(88, 102, 110) !important;
  }

  .header-menu:hover {
    background-color: rgba(0, 0, 0, 0.05);
  }

  .header-user {
    display: inline-block;
    font-size: 14px;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    touch-action: manipulation;
    cursor: pointer;
    border: 1px solid transparent;
    font-weight: 500;
    border-radius: 2px;
    outline: 0 !important;
    margin-top: 8px;
    margin-bottom: 8px;
    float: right;
    margin-right: 10px;
  }

  .ivu-dropdown-item {
    line-height: 20px;
  }
</style>


